<?php

class UploadController extends \BaseController {

	/**
	 * Display a listing of the resource.
	 *
	 * @return Response
	 */
	public function index()
	{
		// First we fetch the Request instance
		$request = Request::instance();
		// Now we can get the content from it
		$content = $request->getContent();

		//$upload_dir = storage_path().'/uploads/'.Auth::User()->username.'/';
		$upload_dir = public_path().'/uploads/'.Auth::User()->username.'/';
		$filename = Request::header('content-file-name');
		$hash_code = Str::limit($filename, (Str::length($filename) - 6), '');
		
		Log::info('Upload dir >> ' . $upload_dir);
		$files = File::files($upload_dir);
		foreach($files as $file_path) {
			$file_name = File::name($file_path);
			$old_hash_code = Str::limit($file_name, Str::length($file_name) - 2, Str::length($file_name));
			if (!Str::startsWith($file_name, $hash_code)) {
				File::delete($file_path);
			}
		}
		
		if (!File::exists($upload_dir)) {
			File::makeDirectory($upload_dir, 0755, true);
			file_put_contents($upload_dir.$filename, $content);
		} else {
			file_put_contents($upload_dir.$filename, $content);
		}
		
		
	}

}
